//暴露husky自动化部署的脚本方法步骤
const cp = require('child_process')
const util = require('util')
const exec = util.promisify(cp.exec)
const path = require('path')
const inquirer = require('inquirer')
const { copyFolder, replaceFile, copyFile } = require('../createFile/create')
const {
  resolve,
  log,
  successLog,
  errorLog,
  showLoading,
  hideLoading,
  getHirtime,
} = require('../utils.js')
const writePkgScript = require('../npmScripts/writePkgScript')
const getPkgScript = require('../npmScripts/getPkgScript')
// const util = require('util');
// const rm = util.promisify(require('shelljs').rm)
// const exec = require('shelljs').exec //|| util.promisify(require('shelljs').exec);
// 可以深度删除依赖包相对于deletefolder方法
// const rm = require('shelljs').rm
const rm = util.promisify(require('rimraf'))
const shelljs = require('shelljs')

// @commitlint/cli                  16.0.0  →  17.1.2
// @commitlint/config-conventional  16.0.0  →  17.1.0
// commitizen                        4.2.4  →   4.2.5
// cz-customizable                   6.3.0  →   6.9.2
// eslint                            8.5.0  →  8.23.0
// husky                             7.0.4  →   8.0.1
// lint-staged                      12.1.4  →  13.0.3
// prettier                          2.5.1  →   2.7.1

module.exports = async () => {
  //核心处理逻辑任务
  async function inquirerFuntion(res) {
    //用yarn安装任务
    const yarnTask = [
      // `yarn global add npm husky@7.0.4 npm-check-updates@latest`,
      `npm --registry https://registry.npm.taobao.org i husky@7.0.4 npm-check-updates@latest -g`,
      `yarn add husky@7.0.4 lint-staged@12.1.4 prettier@2.5.1 @commitlint/cli@16.0.0 @commitlint/config-conventional@16.0.0 commitizen@4.2.4 cz-customizable@6.3.0 eslint@8.5.0 @babel/plugin-proposal-optional-chaining@7.17.12 @babel/plugin-proposal-nullish-coalescing-operator@7.17.12 -D`,
      `yarn install`,
    ]
    //用cnpm安装任务
    const cnpmTask = [
      `cnpm i npm husky@7.0.4 npm-check-updates@latest -g`,
      `cnpm i husky@7.0.4 lint-staged@12.1.4 prettier@2.5.1 @commitlint/cli@16.0.0 @commitlint/config-conventional@16.0.0 commitizen@4.2.4 cz-customizable@6.3.0 eslint@8.5.0
      @babel/plugin-proposal-optional-chaining@7.17.12 @babel/plugin-proposal-nullish-coalescing-operator@7.17.12 --save`,
      `cnpm install`,
    ]
    //用淘宝镜像npm安装任务
    const taobaoNpmTask = [
      // `npm --registry https://registry.npm.taobao.org i npm@latest -g`,
      `npm --registry https://registry.npm.taobao.org i husky@7.0.4 npm-check-updates@latest -g`,
      `npm --registry https://registry.npm.taobao.org i husky@7.0.4 lint-staged@12.1.4 prettier@2.5.1 @commitlint/cli@16.0.0 @commitlint/config-conventional@16.0.0 commitizen@4.2.4 cz-customizable@6.3.0 eslint@8.5.0 @babel/plugin-proposal-optional-chaining@7.17.12 @babel/plugin-proposal-nullish-coalescing-operator@7.17.12 --save`,
      `npm --registry https://registry.npm.taobao.org i`,
    ]
    //用npm安装任务
    const npmTask = [
      // `npm install npm@latest -g`,
      `npm i husky@7.0.4 npm-check-updates@latest -g`,
      `npm i husky@7.0.4 lint-staged@12.1.4 prettier@2.5.1 @commitlint/cli@16.0.0 @commitlint/config-conventional@16.0.0 commitizen@4.2.4 cz-customizable@6.3.0 eslint@8.5.0 @babel/plugin-proposal-optional-chaining@7.17.12 @babel/plugin-proposal-nullish-coalescing-operator@7.17.12 --save`,
      `npm i`,
    ]
    //用pnpm安装任务
    const pnpmTask = [
      `pnpm global add npm husky@7.0.4 npm-check-updates@latest`,
      `pnpm add husky@7.0.4 lint-staged@12.1.4 prettier@2.5.1 @commitlint/cli@16.0.0 @commitlint/config-conventional@16.0.0 commitizen@4.2.4 cz-customizable@6.3.0 eslint@8.5.0 @babel/plugin-proposal-optional-chaining@7.17.12 @babel/plugin-proposal-nullish-coalescing-operator@7.17.12 -D`,
      `pnpm install`,
    ]
    // `ncu husky lint-staged @commitlint/cli  @commitlint/config-conventional commitizen cz-customizable eslint prettier -u`
    const {
      del_modules,
      which_npm,
      script_husky,
      sim_shell,
      script_husky_latest,
    } = res
    let npm = []
    let ncu_script = `ncu husky lint-staged @commitlint/cli  @commitlint/config-conventional commitizen cz-customizable eslint prettier -u`

    // 获取依赖下载包
    switch (which_npm) {
      case 'yarn':
        npm = yarnTask
        break
      case 'cnpm':
        npm = cnpmTask
        break
      case 'npm':
        npm = npmTask
        break
      case 'taobao':
        npm = taobaoNpmTask
        break
      case 'pnpm':
        npm = pnpmTask
        break
      default:
        npm = yarnTask
        break
    }
    // 如果为true 则更新最新的husky依赖
    if (script_husky_latest) {
      npm.push(ncu_script)
    }

    // 删除依赖和文件
    try {
      log('删除本地依赖和.husky文件')
      showLoading()
      // 删除lock文件
      await rm('package-lock.json')
      // 判断是否删除本地依赖包
      if (del_modules) {
        await rm('node_modules')
      }
      await rm('.husky')
      replaceFile('.gitignore', /.*lock(.*)?/gi, '')
      hideLoading()
    } catch (error) {
      errorLog(error)
    }

    /*
    先删除node_modules依赖目录
    await rm("-rf", "node_modules").catch((err) => {})
    await deletefolder('node_modules').catch((err) => {})
    先删除husky文件目录
    await rm("-rf", ".husky").catch((err) => {})
    //循环处理函数
    */
    try {
      log('安装husky需要的依赖包···')
      showLoading()
      for (const item of npm) {
        await exec(item, { cwd: resolve('./') })
      }
      hideLoading()
      log('添加hooks命令等···')
      showLoading()
      log('注: 需要npm版本Version 7.x(npm set-script命令需要7.x)')
      for (const item of script_husky) {
        await exec(item, { cwd: resolve('./') })
      }
      hideLoading()
      log('*生成配置文件···')
      showLoading()
      let huskyFolder = path.join(__dirname, `../template/husky`)
      await copyFolder(huskyFolder, resolve('./'))
      // 新增脚本
      writePkgScript('commit', 'git add . && git cz', true)
      hideLoading()
      successLog('生成配置成功')
      successLog('恭喜你成安装配置husky了！！！')
    } catch (error) {
      errorLog('执行husky流水线配置错误')
      errorLog(error)
    }

    // 切换sim环境配置拷贝正式环境
    try {
      log('安装sim需要的依赖包···')
      showLoading()
      if (sim_shell) {
        shelljs.cp('-R', '.env.production', '.env.sim')
        writePkgScript('build:sim', 'vue-cli-service build --mode sim', true)
      }
      hideLoading()
    } catch (error) {
      errorLog(error)
    }
    hideLoading()
    log('安装husky运行时间：' + getHirtime())
  }

  //运行执行husky任务流水线
  const huskyTask = await inquirer
    .prompt([
      {
        type: 'confirm',
        message: '是否删除本地依赖包？',
        name: 'del_modules',
        prefix: '确认',
        default: true,
      },
      {
        type: 'list',
        name: 'which_npm',
        message: '请选择下载依赖的工具包',
        default: 'taobao',
        choices: ['taobao', 'pnpm', 'yarn', 'cnpm', 'npm'],
        filter: function (val) {
          // 使用filter将回答变为小写
          return val.toLowerCase()
        },
        validate: function (input) {
          var done = this.async()
          if (input == '') {
            done('不能为空')
            return
          }
          done(null, true)
        },
      },
      {
        type: 'input',
        name: 'script_husky',
        message: '运行安装执行脚本添加hooks钩子函数命令等',
        default: [
          `husky install`,
          // `npm set-script prepare "husky install"`, //注释一下husky install安装
          // `npm set-script lint-staged "lint-staged --allow-empty" `,
          `husky add .husky/commit-msg "npx --no-install commitlint --edit $1"`,
          `husky add .husky/pre-commit "npx lint-staged --allow-empty $1"`,
          `husky add .husky/pre-merge-commit "npx lint-staged --allow-empty $1"`,
          // `npm set-script commit "git add . && git cz"`,
          // `yarn husky add .husky/commit-msg "yarn commitlint --edit '$1'"`,
          // `yarn husky add .husky/pre-commit "yarn lint-staged --allow-empty '$1'"`,
        ],
        validate: function (input) {
          var done = this.async()
          if (input == '') {
            done('不能为空')
            return
          }
          done(null, true)
        },
      },
      {
        type: 'confirm',
        message: '是否安装最新的husky依赖',
        name: 'script_husky_latest',
        prefix: '确认',
        default: true,
      },
      {
        type: 'input',
        name: 'script_shell',
        message: '选择运行执行生成husky需要配置的文件',
        default: `../template/husky/*`,
        validate: function (input) {
          var done = this.async()
          if (input == '') {
            done('不能为空')
            return
          }
          done(null, true)
        },
      },
      // {
      //   type: 'confirm',
      //   message: '切换sim环境配置拷贝正式环境(.env.production)',
      //   name: 'sim_shell',
      //   prefix: '确认',
      //   default: true
      // },
    ])
    .then(function (res) {
      //调用主业务逻辑处理方法
      inquirerFuntion(res)
    })
}
